package vn.allmobile.ambnews.activities.main;

import java.util.Calendar;

import vn.allmobile.ambnews.AboutActivity;
import vn.allmobile.ambnews.BaseActivity;
import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.SettingsActivity;
import vn.allmobile.ambnews.activities.list.ListActivity;
import vn.allmobile.ambnews.customview.FlipViewInterface;
import vn.allmobile.ambnews.data.Category;
import vn.allmobile.ambnews.data.Paper;
import vn.allmobile.ambnews.network.LoaderThread;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.network.NetworkChangeReceiver;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.Log;
import vn.allmobile.ambnews.utils.PreferenceManager;
import vn.allmobile.ambnews.utils.Utils;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.aphidmobile.flip.FlipViewController;
import vn.allmobile.ambnews.flipview.FlipView;
import vn.allmobile.ambnews.flipview.OverFlipMode;

public class HomeActivity extends BaseActivity  {
	

	HomeAdapter mAdapter;
	//FlipViewController flipview;
	preloadHotData preload;
	//FlipView flipview;
	//private SlidingLayer mSlidingLayer;
	FlipViewInterface flipview;
	Boolean updating = false;
	int numTask = 0;
	int numTaskComplete = 0;
	//FlipView  flipview;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
				
		try{
			flipview = (FlipView)findViewById(R.id.flipViewHome);
			flipview.setOverFlipMode(OverFlipMode.RUBBER_BAND);
		}catch(Exception e)
		{
			Log.v("flipview Exception");
			flipview = (FlipViewController) findViewById(R.id.flipViewHome);	
		}
		mAdapter = new HomeAdapter(this);
		mAdapter._flipview = flipview;		//
		flipview.setAdapter(mAdapter);
		
		//flipview.setOnFlipListener(this);
		if(!NetworkAPI._appState.isEmpty() || NetworkAPI._appState  != null)
			showNotiVersion();
		if(NetworkAPI._isPaperUpdated)
		{
			NetworkAPI._isPaperUpdated = false;
			Toast.makeText(this, "Có cập nhật mới danh sách báo.",Toast.LENGTH_LONG).show();			
		}
		
		Calendar localCalendar = Calendar.getInstance();
		localCalendar.setTimeInMillis(Utils.currentMillis());			
		int hour = localCalendar.get(Calendar.HOUR_OF_DAY);
		if(hour > 18 && !PreferenceManager.isNightMode())
		{
			Toast.makeText(this, "Ứng dụng hỗ trợ chế độ đọc ban đêm. Vui lòng vào cài đặt để thay đổi.", Toast.LENGTH_LONG).show();
		}
		
	}
	
	
	
	public class preloadHotData extends AsyncTask<Void, Boolean, Boolean> {

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			mAdapter.datachanged();						
			//mAdapter.notifyDataSetInvalidated();
			flipview.refreshPage(0);
			super.onPostExecute(result);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			NetworkAPI._()._loaderThread.loadHotNews();									
			return true;
		}				
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		//flipview = (FlipViewController) findViewById(R.id.flipViewHome);
		//mAdapter = (HomeAdapter) flipview.getAdapter();		
		mAdapter.datachanged();
		mAdapter.notifyDataSetChanged();
		
	}
	
	

	@Override
	  protected void onResume() {
		Log.v("resume");
	    super.onResume();
		updating = false;
		numTask = 0;
		numTaskComplete = 0;
		preload = new preloadHotData();
		preload.execute();
		try{
			LoaderThread.loadUserPaper();
			if(NetworkAPI._userListPapers.size() > 0)
			{
				for(Paper pp : NetworkAPI._userListPapers)
				{
					pp.setUpdating(false);
				}
			}
		}catch(Exception e){
			Log.v("user paper: no user aper");
		}
		mAdapter.datachanged();

	  }

	  @Override
	  protected void onPause() {
	    super.onPause();
	   // flipview.onPause();
	  }
	  
	  
		@Override
		public void onBackPressed() {
			Log.v("Back pressed");
			backPressConfirm();  
			
		}
	  
	  public void backPressConfirm() {
	        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int which) {
	                     switch (which) {
	                     case DialogInterface.BUTTON_POSITIVE:
	                    	 	Process.killProcess(Process.myPid());
	                    	 	finish();
	                            break;

	                     case DialogInterface.BUTTON_NEGATIVE:
	                           
	                            break;
	                     }
	               }
	        };

	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setMessage("Bạn có chắc muốn đóng chương trình?")
	                     .setPositiveButton("Đồng ý", dialogClickListener)
	                     .setNegativeButton("Không", dialogClickListener).show();
	 }


	  private void showNotiVersion() {
			
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					this);
			AlertDialog  alertDiaglog;
			
			if (NetworkAPI._appState.equals(Contants.version_no_support)) {
				Log.v("version_no_support support");
				alertDialogBuilder.setMessage(getString(R.string.text_noti_no_support))
									.setPositiveButton("Đồng Ý", openPlayStoreLitener)
									.setNegativeButton("Không", cancelLitenerNoSupport);
				
					alertDiaglog = alertDialogBuilder.create();
					alertDiaglog.show();		
			}

			if (NetworkAPI._appState.equals(Contants.version_still_support)) {
				Log.v("still support");
				alertDialogBuilder.setMessage(getString(R.string.text_noti_still_support))
					.setPositiveButton("Đồng Ý", openPlayStoreLitener)
					.setNegativeButton("Không", cancelLitenerStillSupport);
		
					alertDiaglog = alertDialogBuilder.create();
					alertDiaglog.show();
		
			}

			
		}

		DialogInterface.OnClickListener openPlayStoreLitener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				PackageInfo pInfo;
				String packageName = "";
				try {
					pInfo = getPackageManager().getPackageInfo(
							getPackageName(), 0);
					packageName = pInfo.packageName;
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try {
					startActivity(new Intent(Intent.ACTION_VIEW,
							Uri.parse("market://details?id=" + packageName)));
				} catch (android.content.ActivityNotFoundException anfe) {
					startActivity(new Intent(
							Intent.ACTION_VIEW,
							Uri.parse("http://play.google.com/store/apps/details?id="
									+ packageName)));
				}
				finish();
			}
		};

		DialogInterface.OnClickListener cancelLitenerNoSupport = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		};

		DialogInterface.OnClickListener cancelLitenerStillSupport = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				
			}
		};
	
		
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void onRefresh(View v){
		if(NetworkChangeReceiver.isConnected(true))	
			if(updating == false)
			{
				updating = true;
				
				try{
					if(NetworkAPI._userListPapers.size() > 0)
					{
						int index = 0;
						for(Paper pp : NetworkAPI._userListPapers)
						{
							numTask ++;
							/*for(Category cat : pp.getCategories())
							{						
							
							}*/
							refreshTask task  = new refreshTask(index,pp);					
							if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {				
								task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
							}
							else {				
								task.execute();
							}
							index ++;
							
						}
					}
				}catch(Exception e){
					Log.v("user paper: no user aper");
				}		
			}	
		
	}
		
		
	private class refreshTask extends AsyncTask<Void, Boolean, Boolean> {

		Paper pp;
		int index;
		refreshTask(int index,Paper pp)
		{
			this.index = index;
			this.pp = pp;
		}
		@Override
		protected void  onPreExecute()
		{			
			if(updating)
			{
				NetworkAPI._userListPapers.get(index).setUpdating(true);
				mAdapter.notifyDataSetChanged();				
			}
			super.onPreExecute();			
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(updating)
			{
				NetworkAPI._userListPapers.get(index).setUpdating(false);
				Log.v("index:" + index + " updating :" + NetworkAPI._userListPapers.get(index).isUpdating());
				numTaskComplete ++;
				if(numTask <= numTaskComplete)
				{
					updating = false;
				}
				Log.v("numTask:" + numTask + " taskComplete:" + numTaskComplete);
				mAdapter.notifyDataSetChanged();
			}						
			super.onPostExecute(result);
		}
		@Override
		protected Boolean doInBackground(Void... params) {
			if(updating)
			{	
				for(Category cat : pp.getCategories())
				{					
					NetworkAPI._()._loaderThread.loadListArticle(pp.getId(),cat.getId(),true);
				}
				
			}
			return null;
		}
	}	
	public void onHotNewsClick(View v)
	{
		try{
			if(NetworkAPI._listHotArticles.size() > 0)
			{
				Intent mIntent = new Intent(this, ListActivity.class);
				mIntent.putExtra(Contants.EXTRA_LIST_TYPE, Contants.LIST_TYPE_HOT);
				startActivity(mIntent);
			}
			
		}catch(Exception e){e.printStackTrace();}
		
	}
	public void onAllNewsClick(View v)
	{
		Intent localIntent = new Intent(this, MainActivity.class);		
		startActivity(localIntent);
	}
	public void onSettingClick(View v)
	{
		Intent mIntent = new Intent(this, SettingsActivity.class);			
		startActivity(mIntent);
	}
	
	public void onMoreClick(View v)
	{
		Intent mIntent = new Intent(this, MainAllPapersActivity.class);			
		startActivity(mIntent);	
	}
	
}
